package com.atguigu.gulimall.order.rabbit.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.rabbit.constant.OrderRabbitConstant;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/19 9:07
 */
@Slf4j
@Component
@RabbitListener(queues = OrderRabbitConstant.ORDER_RELEASE_ORDER_QUEUE)
public class OrderListener {
    
    @Autowired
    OrderService orderService;
    
    @RabbitHandler
    public void handlerOrderRelease(OrderEntity order, Message message, Channel channel) throws IOException {
        try {
            log.info("订单超时解锁库存：{}", JSONObject.toJSONString(order));
            orderService.releaseOrder(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
    
}
